package com.zego.wawaji.third.share;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.open.GameAppOperation;
import com.tencent.tauth.Tencent;
import com.zego.wawaji.R;
import com.zego.wawaji.base.module.ModuleMgr;
import com.zego.wawaji.base.toast.PToast;
import com.zego.wawaji.http.request.RequestComplete;
import com.zego.wawaji.third.ThirdConstant;
import com.zego.wawaji.third.share.data.ShareData;
import com.zego.wawaji.third.share.util.QQShareListener;
import com.zego.wawaji.third.share.util.ShareEnum;

import java.util.ArrayList;
import java.util.List;

/**
 * 分享集合工具类
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
public class ShareUtils {
    private static final int THUMB_SIZE_W = 500;
    private static final int THUMB_SIZE_H = 500;

    public static final int SHARE_NORMAL = 0;  // 普通分享
    public static final int SHARE_REWARD = 1;  // 每日礼包分享
    public static int shareChannel = SHARE_NORMAL;   // 分享渠道 0：普通分享   1： 每日礼包分享

    private IWXAPI api;

    private static ShareUtils mInstance;

    public static ShareUtils getInstance() {
        if (mInstance == null) {
            mInstance = new ShareUtils();
        }
        return mInstance;
    }

    private static ShareData shareData;

    public ShareData getShareData() {
        if (shareData == null) {
            shareData = new ShareData();
        }
        return shareData;
    }

    /**
     * 服务端获取分享数据
     */
    public void reqShareData(final RequestComplete complete) {
        ModuleMgr.getWawaMgr().reqShareInfo(response -> {
            if (!response.isOk()) return;
            shareData = (ShareData) response.getBaseData();
            if (complete != null)
                complete.onRequestComplete(response);
        });
    }

    /**
     * 解析分享数据 并执行分享
     */
    public void shareData(Activity context, ShareEnum shareEnum) {
        if (shareData == null) {
            PToast.showShort("获取分享数据失败，请稍后重试");
            reqShareData(null);
            return;
        }
        shareData.setShareEnum(shareEnum);
        onShare(context, shareEnum, shareData, new ShareCallBack() {
            @Override
            public void shareSuccess(ShareEnum shareEnum, final ShareData shareData) {
                if (shareEnum == ShareEnum.COPY) {
                    PToast.showLong("复制到粘贴板成功，可直接发送给好友哦");
                    return;
                }
                PToast.showShort("分享成功");
            }

            @Override
            public void shareFail(ShareEnum shareEnum, ShareData shareData) {
                PToast.showShort("分享失败, 请稍后重试");
            }
        });
    }

    /**
     * 分享到哪个平台
     */
    private void onShare(Activity activity, final ShareEnum shareEnum, ShareData shareData, final ShareCallBack shareCallBack) {
        if (shareEnum == ShareEnum.WEIXIN || shareEnum == ShareEnum.WEIXIN_FRIENDS) {
            // 通过WXAPIFactory工厂，获取IWXAPI的实例
            api = WXAPIFactory.createWXAPI(activity, ThirdConstant.WEIXIN_APP_ID, true);
            // 将该app注册到微信
            api.registerApp(ThirdConstant.WEIXIN_APP_ID);
        }
//        if (shareEnum == ShareEnum.WEIBO) {
//            registerWeibo(activity);
//        }

        switch (shareEnum) {
            case QQ:
                setShareListener(new QQShareListener());
                getShareListener().setShareData(shareData);
                shareToQQ(activity, shareEnum, shareData, shareCallBack);
                break;
            case QQ_ZONE:
                setShareListener(new QQShareListener());
                getShareListener().setShareData(shareData);
                shareToQQzone(activity, shareEnum, shareData, shareCallBack);
                break;
            case QQ_TROOP:
                setShareListener(new QQShareListener());
                getShareListener().setShareData(shareData);
                shareToTroopBar(activity, shareEnum, shareData, shareCallBack);
                break;
            case WEIBO:
//                shareToWeibo(activity, shareData);
                break;
            case WEIXIN:
                shareToWeixin(activity, shareData);
                break;
            case WEIXIN_FRIENDS:
                shareTofriends(activity, shareData);
                break;
            case SMS:
                toSMS(activity, shareEnum, shareData);
                break;
            case COPY:
                copyContent(activity, shareEnum, shareData, shareCallBack);
                break;
            case BROWSER:
                toBrowser(activity, shareData);
                break;
        }
    }

    //qq 分享监听事件
    private QQShareListener shareListener;

    public QQShareListener getShareListener() {
        return shareListener;
    }

    public void setShareListener(QQShareListener shareListener) {
        this.shareListener = shareListener;
    }

    /**
     * 分享到QQ
     */
    // http://wiki.open.qq.com/wiki/mobile/API%E8%B0%83%E7%94%A8%E8%AF%B4%E6%98%8E
    private void shareToQQ(final Activity activity, final ShareEnum shareEnum, final ShareData shareData, final ShareCallBack shareCallBack) {

        final Tencent mTencent = Tencent.createInstance(ThirdConstant.QQ_APP_ID, activity);
        final Bundle params = new Bundle();
        //params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_APP);
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, shareData.getTitle());
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareData.getRedirect());
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, shareData.getImg());
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "返回");
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, shareData.getInfo());
        getShareListener().setShareCallBack(shareCallBack);
        mTencent.shareToQQ(activity, params, getShareListener());
    }

    /**
     * 分享到qq空间
     */
    private void shareToQQzone(final Activity activity, final ShareEnum shareEnum, final ShareData shareData, final ShareCallBack shareCallBack) {
        final Tencent mTencent = Tencent.createInstance(ThirdConstant.QQ_APP_ID, activity);
        final Bundle params = new Bundle();
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, shareData.getTitle());//必填
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, shareData.getInfo());//选填
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, shareData.getRedirect());//必填
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add(shareData.getImg());
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, arrayList);
        getShareListener().setShareCallBack(shareCallBack);
        mTencent.shareToQzone(activity, params, getShareListener());
    }

    /**
     * 分享到群部落: 不能使用，有问题
     */
    private void shareToTroopBar(final Activity activity, final ShareEnum shareEnum, final ShareData shareData, final ShareCallBack shareCallBack) {
        final Tencent mTencent = Tencent.createInstance(ThirdConstant.QQ_APP_ID, activity);
        final Bundle params = new Bundle();
        params.putString(GameAppOperation.QQFAV_DATALINE_APPNAME, "呆萌抓娃娃");
        params.putString(GameAppOperation.QQFAV_DATALINE_TITLE, shareData.getTitle());
        params.putString(GameAppOperation.QQFAV_DATALINE_DESCRIPTION, shareData.getInfo());
//        params.putString(GameAppOperation.TROOPBAR_ID, troopbarId.getText().toString());
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add(shareData.getImg());
        params.putStringArrayList(GameAppOperation.QQFAV_DATALINE_FILEDATA, arrayList);
        getShareListener().setShareCallBack(shareCallBack);
        mTencent.shareToTroopBar(activity, params, getShareListener());
    }

    // =================================== 微博相关 ========================================================
//    private WbShareHandler shareHandler;
//
//    /**
//     * 注册应用到微博
//     */
//    private void registerWeibo(Activity activity) {
//        if (shareHandler != null) return;
//        WbSdk.install(activity, new AuthInfo(activity, ThirdConstant.WEIBO_APP_KEY, ThirdConstant.REDIRECT_URL, ThirdConstant.SCOPE));
//        shareHandler = new WbShareHandler(activity);
//        shareHandler.registerApp();
//    }
//
//    public void setWeiboCallback(Activity activity, Intent intent) {
//        if (shareHandler == null)
//            registerWeibo(activity);
//
//        shareHandler.doResultIntent(intent, new WbShareCallback() {
//            @Override
//            public void onWbShareSuccess() {
//                PToast.showShort("分享成功");
//            }
//
//            @Override
//            public void onWbShareCancel() {
//                PToast.showShort("分享取消");
//            }
//
//            @Override
//            public void onWbShareFail() {
//                PToast.showShort("分享失败");
//            }
//        });
//    }
//
//    /**
//     * 新浪微博分享
//     */
//    private void shareToWeibo(final Activity activity, final ShareData shareData) {
//        if (shareHandler == null) {
//            registerWeibo(activity);
//        }
//        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
//        weiboMessage.textObject = getTextObj();       // 文本消息
////        weiboMessage.imageObject = getImageObj();     // 带默认图片
////        weiboMessage.multiImageObject = getMultiImageObject(); // 带多个默认图片
////        weiboMessage.videoSourceObject = getVideoObject();  // 带视频文件
//        weiboMessage.mediaObject = getWebpageObj();
//        shareHandler.shareMessage(weiboMessage, false);
//    }
//
//    /**
//     * 创建文本消息对象。
//     *
//     * @return 文本消息对象。
//     */
//    private TextObject getTextObj() {
//        TextObject textObject = new TextObject();
//        if (shareData != null) {
//            textObject.text = "@呆萌抓娃娃，" + shareData.getInfo() + " #呆萌抓娃娃#http://weibo.com/u/6505842150"
//                    + "  戳链接下载APP领取奖励 —>";
//        }
//        return textObject;
//    }
//
//    /**
//     * 创建多媒体（网页）消息对象。
//     *
//     * @return 多媒体（网页）消息对象。
//     */
//    private WebpageObject getWebpageObj() {
//        WebpageObject mediaObject = new WebpageObject();
//        if (shareData != null) {
//            mediaObject.identify = Utility.generateGUID();
//            mediaObject.title = shareData.getTitle();
//            mediaObject.description = shareData.getInfo();
//            Bitmap bitmap = BitmapFactory.decodeResource(AppTinkerLike.getActivity().getResources(), R.drawable.ic_launcher01);
//            // 设置 Bitmap 类型的图片到视频对象里    设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
//            mediaObject.setThumbImage(bitmap);
//            mediaObject.actionUrl = shareData.getRedirect();
//            mediaObject.defaultText = "呆萌抓娃娃";
//        }
//        return mediaObject;
//    }

    // =========================================== 微信相关 ========================================

    /**
     * 分享到微信朋友圈
     */
    private void shareTofriends(Activity activity, ShareData shareData) {
        toWeixin(activity, shareData, false);
    }

    /**
     * 分享到微信
     */
    private void shareToWeixin(Activity activity, ShareData shareData) {
        toWeixin(activity, shareData, true);
    }

    /**
     * 微信分享到朋友圈
     */
    private void toWeixin(final Activity activity, ShareData shareData, final boolean isFriend) {
        if (!api.isWXAppInstalled()) {
            PToast.showShort("未安装微信");
            return;
        }

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = shareData.getRedirect();
        final WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = shareData.getTitle();
        msg.description = shareData.getInfo();
        msg.setThumbImage(BitmapFactory.decodeResource(activity.getResources(), R.drawable.ic_launcher01));

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = isFriend ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
        api.sendReq(req);
    }

    /**
     * 短信分享
     */
    private void toSMS(Activity activity, final ShareEnum shareEnum, ShareData shareData) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setType("vnd.android-dir/mms-sms");
        intent.putExtra("sms_body", shareData.getInfo() + " 请点击:" + shareData.getRedirect());
        activity.startActivity(intent);
    }

    /**
     * 将分享链接复制到剪切板（redirect字段）
     */
    private void copyContent(Activity activity, final ShareEnum shareEnum, ShareData shareData, final ShareCallBack shareCallBack) {
        if (Build.VERSION.SDK_INT > 11) {
            // 得到剪贴板管理器
            android.content.ClipboardManager clipboard = (android.content.ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
            clipboard.setPrimaryClip(ClipData.newPlainText("Label", shareData.getRedirect()));
        } else {
            android.text.ClipboardManager cmb = (android.text.ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
            cmb.setText(shareData.getRedirect());
        }
        shareCallBack.shareSuccess(shareEnum, shareData);
    }

    /**
     * 浏览器打开所分享的跳转页面： 利用浏览器的分享功能分享
     */
    private void toBrowser(Activity activity, ShareData shareData) {
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.BROWSABLE");
        intent.addCategory("android.intent.category.DEFAULT");
        Uri uri = Uri.parse("http://");
        intent.setDataAndType(uri, null);
        PackageManager packageManager = activity.getPackageManager();

        // 找出手机当前安装的所有浏览器程序
        List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(intent, PackageManager.GET_INTENT_FILTERS);
        if (resolveInfoList == null && resolveInfoList.size() < 1) {
            PToast.showShort("请安装浏览器!");
            return;
        }

        Intent intent_browser = new Intent(Intent.ACTION_VIEW, Uri.parse(shareData.getRedirect()));
        activity.startActivity(intent_browser);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    public interface ShareCallBack {
        void shareSuccess(ShareEnum shareEnum, ShareData shareData);

        void shareFail(ShareEnum shareEnum, ShareData shareData);
    }
}
